package tech.yunland.shop.domain.service;

import com.moyuer.bsf.domain.dao.UserDao;
import com.moyuer.bsf.domain.model.HqlArgs;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.GoodsDao;
import tech.yunland.shop.domain.dao.GoodsPaidDao;
import tech.yunland.shop.domain.model.Goods;
import tech.yunland.shop.domain.model.GoodsPaid;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 预购商品服务类
 * 
 * @author 王睿智 <geekrize@gmail.com>
 */
@Service
public class GoodsPaidService {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GoodsPaidDao goodsPaidDao;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private GoodsDao goodsDao;
	
	@Autowired
	private UserDao userDao;


	/**
	 * 保存或修改
	 * 
	 * @param goodsPaid
	 */
	public void saveOrUpdate(GoodsPaid goodsPaid) {
		goodsPaidDao.saveOrUpdate(goodsPaid);

	}

	/**
	 * 查找指定机构下的预购商品
	 * 
	 * @param userId
	 * @param organId
	 * @return List<GoodsPaid>
	 */
	public List<GoodsPaid> getList(String userId, String organId) {
		userId = StringUtils.trimToNull(userId);
		organId = StringUtils.trimToNull(organId);

		if (userId == null && organId == null) {
			return null;
		}

		DetachedCriteria criteria = DetachedCriteria.forClass(GoodsPaid.class);
		if (userId != null) {
			// criteria.add(Restrictions.eq("member", userId));
			criteria.createCriteria("member").add(Restrictions.idEq(userId));
		}

		if (organId != null) {
			criteria.createCriteria("organ").add(Restrictions.idEq(organId));
		}

		criteria.addOrder(Order.desc("lastModify"));

		return goodsPaidDao.findByCriteria(criteria);
	}

	/**
	 * 根据条件生成查询语句
	 * 
	 * @param userId
	 * @param organId
	 * @return
	 */
	private HqlArgs genHqlArgs(List<String> goodsId, String userId, List<String> organIds) {

		Map<String, Object> args = new HashMap<String, Object>();

		String hql = "from GoodsPaid g where 1=1 ";
		if (userId != null) {
			hql += " and g.member.id = :userId ";
			args.put("userId", userId);
		}

		if (goodsId != null && goodsId.size() > 0) {
			if (goodsId.size() == 1) {
				hql += " and g.goods.id = :goodsId ";
				args.put("goodsId", goodsId);
			} else {
				hql += " and g.goods.id in :goodsId ";
				args.put("goodsId", goodsId);
			}
		}

		if (organIds != null && organIds.size() > 0) {
			if (organIds.size() == 1) {
				hql += " and g.organ.id = :organId ";
				args.put("organId", organIds.get(0));
			} else {
				hql += " and g.organ.id in :organId ";
				args.put("organId", organIds);
			}
		}

		return new HqlArgs(hql, args);

	}

	/**
	 * 根据入参查询结果数量 GoodsPaid
	 * 
	 * @param goodsId
	 * @return
	 */
	public int getResultSize(List<String> goodsId, String userId, List<String> organIds) {

		HqlArgs hqlArgs = genHqlArgs(goodsId, userId, organIds);

		return (int) goodsPaidDao.getCount(hqlArgs.getHql(), hqlArgs.getArgs());
	}

	/**
	 * 根据参数返回结果集 GoodPaid
	 * 
	 * @param userId
	 *            会员ID
	 * @param startIndex
	 * @param length
	 * @param organIds
	 * @return List<GoodsPaid>
	 */
	public List<GoodsPaid> getResultInfos(List<String> goodsId, String userId, Integer startIndex, Integer length,List<String> organIds) {
		HqlArgs hqlArgs = genHqlArgs(goodsId, userId, organIds);

		String hql = "select g " + hqlArgs.getHql() + " order by g.lastModify desc,g.quantity desc";

		return goodsPaidDao.findByNamedParam(hql, startIndex, length, hqlArgs.getArgs());
	}

	/**
	 * 查询规定店铺下商品的会员平均价格
	 * 
	 * @param organId
	 * @param goodsId
	 * @return
	 */
	public List<Map<String, Object>> getMemberPrize(String organId, String goodsId) {

		return goodsDao.getMemberPrize(organId, goodsId);

	}

	/**
	 * 查询全部会员剩余商品价值
	 * 
	 * @param organId
	 * @return
	 */
	public List<Map<String, Object>> getReservedGoods(String organId) {

		String sql = " select sum(amount) as amount from goods_paid where organ_id='" + organId + "' ";

		return jdbcTemplate.queryForList(sql);
	}
	
	

	/**
	 * 按会员查询剩余总额
	 * 
	 * @param organId
	 * @return
	 */
	public List<Map<String, Object>> getMemberReserved(String organId,Integer page,Integer row,String returnType) {

		return goodsPaidDao.getMemberReserved(organId, page, row,returnType);
	}
	/**
	 * 按会员名称模糊查询剩余总额
	 *
	 * @param param
	 * @return
	 */
	public List<Map<String, Object>> getMemberReservedLike(String organId,String param,Integer page,Integer row,String returnType){

		return goodsPaidDao.getMemberReservedLike(organId,param, page, row,returnType);
	}

	/**
	 * 按会员查询明细
	 * 
	 * @param organId
	 * @param userId
	 * @return
	 */
	public List<Map<String, Object>> getReservedEntry(String organId, String userId, Integer page,Integer row,String returnType) {

		return goodsPaidDao.getReservedGoods(organId, userId, page, row,returnType);

	}


/**
	 * 查询热门商品购买力信息
	 * @param dateType
	 * @param primaryOrganId
	 * @param bizDate
	 * @return
	 */
	public List<Map<String,Object>>getTopInfo(String dateType, String bizDate,String organId ,Integer page,Integer rows,String returnType){
		
		return goodsPaidDao.getTopInfo(dateType, bizDate,organId,  page, rows, returnType);
		
	}

	/**
	 * 查询顾客消费信息
	 * @param dateType
	 * @param bizDate
	 * @param organId
	 * @param page
	 * @param rows
	 * @param returnType
	 * @return
	 */
	public List<Map<String, Object>> getShopInfo(String dateType, String bizDate,String organId ,Integer page,Integer rows,String returnType){
		
		return goodsPaidDao.getShopInfo(dateType, bizDate,organId,  page, rows, returnType);
	}

	/**
	 * 查询会员的消费能力
	 * @param dateType
	 * @param bizDate
	 * @param memberId
	 * @param page
	 * @param rows
	 * @param returnType
	 * @return
	 */
	public List<Map<String, Object>> getMemberShopInfo(String dateType,String bizDate,String memberId,Integer page, Integer rows,String returnType){
	
		return goodsPaidDao.getMemberShopInfo(dateType,bizDate, memberId, page,rows,returnType);
	}

	/**
	 * 查询顾客消费活跃度
	 * @param dateType
	 * @param bizDate
	 * @param memberId
	 * @param page
	 * @param rows
	 * @param returnType
	 * @return
	 */
	public List<Map<String, Object>> getShopTimes(String organId,String dateType,String bizDate,String memberId,Integer page, Integer rows,String returnType){
	
		return goodsPaidDao.getShopTimes(organId, dateType, bizDate, memberId, page, rows, returnType);
	}
	
	/**
	 * 会员退卡
	 * @param memberId
	 * @param money
	 * @param organId
	 * @param goodsPaidId
	 * @param goodsId
	 * @param number
	 */
	public void updateMemberCard(String memberId,BigDecimal money,String organId,String goodsPaidId,String goodsId, BigDecimal number){	
		
		//获取会员已购商品
		GoodsPaid goodPaid=goodsPaidDao.get(goodsPaidId);
		
		//获取goods
		Goods goods = goodsDao.get(goodsId);
		String name=goods.getName();
		
		BigDecimal amount1=goodPaid.getAmount(); //剩余金额
		BigDecimal quantity1 = goodPaid.getQuantity();//剩余数量
		BigDecimal amount = BigDecimal.ZERO; 
		BigDecimal quantity = BigDecimal.ZERO;  
		
		if(!name.equals("积分")&&quantity1.compareTo(number) == 0){//全部退完
			goodsPaidDao.deleteObject(goodPaid);
		}else if(!name.equals("积分")&&amount1.compareTo(number)==1){//退一部分
			quantity=quantity1.subtract(number);
			amount=quantity.multiply(amount1.divide(quantity1));
			goodPaid.setAmount(amount);
			goodPaid.setQuantity(quantity);
			goodsPaidDao.update(goodPaid);
		}else if(!name.equals("积分")&&quantity1.compareTo(number) == -1){
			throw new RuntimeException("退卡次数能大于剩余次数！");
		}else{
			throw new RuntimeException("积分不能兑现！");
		}
		
	}

	
	public GoodsPaid getGoodsPaid(String id) {
		return goodsPaidDao.get(id);
	}


	public Map getMemberBalance(String organId, String memberId){
		Map<String, Object> memberBalance = goodsPaidDao.getMemberBalance(organId, memberId);
		return memberBalance;
	}
	
}







